package dao;

import hibernate.HibernateUtil;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Repository;

@Repository
public  class BaseDaoImpl<T> implements BaseDao<T> {

	public void insert(T objectT) {
		Session session=HibernateUtil.getSession();
		session.beginTransaction();
		session.save(objectT);
		session.getTransaction().commit();
		HibernateUtil.closSession(session);
		
	}

	@SuppressWarnings("unchecked")
	public List<T> find(String sql, List<Object> praram) {
		Session session=HibernateUtil.getSession();
		Query q=session.createQuery(sql);
		if(praram!=null&&praram.size()>0){
			for(int i=0;i<praram.size();i++)
				q.setParameter(i, praram.get(i));
		}
		return q.list();
	}

	public Query findPage(String sql, List<Object> param) {
		Session session=HibernateUtil.getSession();
		Query q=session.createQuery(sql);
		if(param!=null &&param.size()>0){
			for(int i=0;i<param.size();i++)
				q.setParameter(i, param.get(i));
		}
				
		return q;
	}
	@SuppressWarnings("unchecked")
	public T findById(Class<T>tclass,int id){
		Session session=HibernateUtil.getSession();
		T object=(T) session.get(tclass, id);
		return object;
	}
	public void update(String sql, List<Object> param) {
		Session session =HibernateUtil.getSession();
		session.beginTransaction();
		Query q= session.createQuery(sql);
		if(param!=null&&param.size()>0){
			for(int i=0;i<param.size();i++)
				q.setParameter(i, param.get(i));
			
		}
		q.executeUpdate();
		session.getTransaction().commit();
		HibernateUtil.closSession(session);
		
	}

	@SuppressWarnings("unchecked")
	public void delete(Class<T> tclass, int id) {
		Session session=HibernateUtil.getSession();
		session.beginTransaction();
		T t=(T) session.get(tclass, id);
		session.beginTransaction();
		session.delete(t);
		session.getTransaction().commit();
		HibernateUtil.closSession(session);
		
	}

	@SuppressWarnings("unchecked")
	public List<T> randomFind(String sql, int number) {
		Session session=HibernateUtil.getSession();
		Query q=session.createQuery(sql);
		List<T>list=q.list();
		List<T>result=new ArrayList<T>();
		int totalrow=list.size();
		Random rd=new Random();
		for(int i=0;i<number;i++){
			int x=rd.nextInt(totalrow-i);
			result.add(list.get(x));
			list.remove(x);
			
		}
		return result;
	}
	
}
